package com.wssnail.sms.config;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.teaopenapi.models.Config;
import com.wssnail.sms.properties.SmsProperties;
import com.wssnail.sms.sender.SmsSender;
import com.wssnail.sms.sender.SmsSenderImpl;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: 熟透的蜗牛
 * @CreateTime: 2022-07-11 16:32
 * @Description: 发送短信自动装配的类
 * @Version: 1.0
 */
@Configuration
@EnableConfigurationProperties(SmsProperties.class)
public class SmsAutoConfig {

    @Autowired
    private SmsProperties smsProperties;

    @Bean
    Config config() {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(smsProperties.getAccessKeyId())
                // 您的 AccessKey Secret
                .setAccessKeySecret(smsProperties.getAccessKeySecret());
        // 访问的域名
        config.endpoint = smsProperties.getDomain();
        return config;
    }

    @Bean
    Client client() throws Exception {
        return new Client(config());
    }

    @Bean
    AsyncClient asyncClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(smsProperties.getAccessKeyId())
                .accessKeySecret(smsProperties.getAccessKeySecret())
                .build());
        AsyncClient asyncClient = AsyncClient.builder()
                .region(smsProperties.getRegionId()) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                           .setEndpointOverride(smsProperties.getDomain())
                ).build();
        return asyncClient;
    }

    @Bean
    @ConditionalOnMissingBean
    SmsSender smsSender() throws Exception {
        return new SmsSenderImpl(asyncClient(),client(),smsProperties);
    }
}
